package purchasePlan

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CreatePurchasePlanApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCreatePurchasePlanApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CreatePurchasePlanApiLogic {
	hostname, _ := os.Hostname()
	return &CreatePurchasePlanApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CreatePurchasePlanApiLogic) CreatePurchasePlanApi(req *types.CreatePurchasePlanReq) (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	// 判断当前是否已经生成了采购计划
	for _, item := range req.IdList {
		_, err = service.PurchasePlanOrdersService.GetByOrdersDetailIdApi(l.ctx, item)
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return "", errors.New("该商品已发布采购计划")
		}
	}

	//orderDetailBos, err := service.OrdersDetailService.GetByIdListApi(l.ctx, req.IdList)
	orderDetailBos, err := service.OrdersSpuService.GetListByIDApi(l.ctx, req.IdList)
	if err != nil || len(orderDetailBos) == 0 {
		return "", errors.New("传递的订单详情id错误")
	}
	for _, item := range orderDetailBos {
		if item.PurchaseStatus != 0 {
			return "", errors.New("传递的订单详情状态有不是待采购的")
		}
		// 判断如果已经分拣的单也不能生成采购计划
		_, err = service.ProductionSortingService.GetPackedList(l.ctx, item.ID)
		//_, err = service.StoreSortingService.GetStoreSortingByOrderIdApi(l.ctx, item.OrdersID)
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return "", errors.New("该订单已经分拣，不能生成采购计划")
		}
	}

	// 拿到这批订单所对应的所有的商品以及他的需求量
	//spuMap, err := service.OrdersDetailService.GetSpuBomByDetailsApi(l.ctx, orderDetailBos)
	//// 根据每个商品的需求量求原材料的需求量
	//spuRequire, err := service.SpuService.GetOrgRequireBySpu(l.ctx, accountInfo.EnterpriseId, spuMap)
	spuRequire, err := service.OrdersSpuService.GetOrgRequireByIDs(l.ctx, accountInfo.EnterpriseId, req.IdList)
	if err != nil {
		return "", err
	}

	// 生成采购计划单
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	for spuID, item := range spuRequire {
		// 判断如果已经生成了采购单的要重新生成采购计划
		purchasePlanEntity, err := service.PurchasePlanService.GetPurchasePlanApi(l.ctx, accountInfo.EnterpriseId, spuID, item.Entity.SupplierID, 0, item.ExpectationGoodsDate)
		var purchasePlanId int64
		if errors.Is(err, gorm.ErrRecordNotFound) {
			purchasePlanEntityData := model.PurchasePlanEntity{
				OrderNo:                 utils.GenerateTodayOrderNo(l.svcCtx.RedisDb, "CG"), // 操作流水号
				EnterpriseID:            accountInfo.EnterpriseId,                           // 关联到enterprise表主键id
				PurchaserID:             0,                                                  // 采购员,关联到
				SupplierID:              item.Entity.SupplierID,                             // 供应商
				DefaultSupplierID:       item.Entity.SupplierID,                             // 默认供应商
				SpuID:                   item.Entity.ID,                                     // 商品,关联到spu表主键id
				SnapshotSpuName:         item.Entity.Name,                                   // '快照商品名称
				SnapshotProductImageURL: item.Entity.ProductImageURL,                        // 快照产品图片
				SnapshotSpuType:         item.Entity.SpuType,                                // 快照商品类型,0表示基础商品,1表示加工商品
				SnapshotUnit:            item.Entity.UnitName,                               // 快照单位
				SnapshotCategory:        item.Entity.CategoryName,                           // 快照分类
				SnapshotCategoryID:      item.Entity.CategoryId,                             // 快照分类
				LossRate:                item.Entity.LossRate,                               // 损耗率                                  // 快照损耗率
				ExpectationGoodsDate:    item.ExpectationGoodsDate,                          // 期望收货日期
				RequirementsCount:       item.Count,                                         // 需求数量
				SnapshotPrice:           item.Entity.SalesPrice,                             // 快照商品单价
				Source:                  0,                                                  // 来源,0表示pc端手动点击订单,1表示定时任务,2表示手机端创建,3pc端手动创建
			}
			if err = service.PurchasePlanService.CreateApi(l.ctx, tx, &purchasePlanEntityData); err != nil {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("创建失败")
			}
			purchasePlanId = purchasePlanEntityData.ID
		} else {
			_, err = service.PurchaseOrderDetailService.GetByPurchasePlanIdApi(l.ctx, purchasePlanEntity.ID)
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 更新数据
				requirementsCount := purchasePlanEntity.RequirementsCount.Add(item.Count)
				fmt.Println(purchasePlanEntity.RequirementsCount, "之前采购计划数量:", item.Count)
				if err = service.PurchasePlanService.ModifyRequirementsCountByIdApi(l.ctx, tx, purchasePlanEntity.ID, requirementsCount); err != nil {
					if err = tx.Rollback(); err != nil {
						return "", err
					}
					return "", errors.New("创建失败")
				}
				purchasePlanId = purchasePlanEntity.ID
			} else {
				purchasePlanEntityData := model.PurchasePlanEntity{
					OrderNo:                 utils.GenerateTodayOrderNo(l.svcCtx.RedisDb, "CG"), // 操作流水号
					EnterpriseID:            accountInfo.EnterpriseId,                           // 关联到enterprise表主键id
					PurchaserID:             0,                                                  // 采购员,关联到
					SupplierID:              item.Entity.SupplierID,                             // 供应商
					DefaultSupplierID:       item.Entity.SupplierID,                             // 默认供应商
					SpuID:                   spuID,                                              // 商品,关联到spu表主键id
					SnapshotSpuName:         item.Entity.Name,                                   // '快照商品名称
					SnapshotProductImageURL: item.Entity.ProductImageURL,                        // 快照产品图片
					SnapshotSpuType:         item.Entity.SpuType,                                // 快照商品类型,0表示基础商品,1表示加工商品
					SnapshotUnit:            item.Entity.UnitName,                               // 快照单位
					SnapshotCategory:        item.Entity.CategoryName,                           // 快照分类
					SnapshotCategoryID:      item.Entity.CategoryId,                             // 快照分类
					LossRate:                item.Entity.LossRate,                               // 损耗率                                  // 快照损耗率
					ExpectationGoodsDate:    item.ExpectationGoodsDate,                          // 期望收货日期
					RequirementsCount:       item.Count,                                         // 需求数量
					SnapshotPrice:           item.Entity.SalesPrice,                             // 快照商品单价
					Source:                  0,                                                  // 来源,0表示pc端手动点击订单,1表示定时任务,2表示手机端创建,3pc端手动创建
					//Remark:                  item.Remark,                                        // 备注
				}
				if err = service.PurchasePlanService.CreateApi(l.ctx, tx, &purchasePlanEntityData); err != nil {
					if err = tx.Rollback(); err != nil {
						return "", err
					}
					return "", errors.New("创建失败")
				}
				purchasePlanId = purchasePlanEntityData.ID
			}
		}
		// 插入到记录表
		if err = service.PurchasePlanOrdersService.CreateApi(l.ctx, tx, &model.PurchasePlanOrdersEntity{
			PurchasePlanID: purchasePlanId,   // 关联到purchase_plan表主键id
			OrdersSpuID:    item.OrdersSpuID, // 关联到orders_spu表主键id
		}); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("创建失败")
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("创建失败")
	}
	return "操作成功", nil
}
